﻿using _2008A.PH5._0221_0317.FuXi.Domain;
using _2008A.PH5._0221_0317.FuXi.IRespository;
using _2008A.PH5._0221_0317.FuXi.IService;
using _2008A.PH5._0221_0317.FuXi.Service;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace _2008A.PH5._0221_0317.FuXi.Service
{
    public class CategoryService : BaseService<CategoryEntity>, ICategoryService
    {
        ICategoryRespository _respository;
        public CategoryService(ICategoryRespository respository, IUnitOfWork unitOfWork) : base(respository, unitOfWork)
        {
            _respository = respository;
        }

        private void _RecursionCategory()
        {
            //先拿所有数据，然后根据父ID去找
            var data = _respository.Query().ToList();

            //先找一级分类
            var list = data.Where(x => x.PId == Guid.Empty).ToList();

            //然后去一级分类，循环找它对应的二级
            list.ForEach(x =>
            {
                //这是第二级
                var second = data.Where(p => p.PId == x.Id).ToList();

                //然后去二级里循环找它对应的三级
                second.ForEach(f =>
                {
                    //这是第三级
                    var third = data.Where(k => k.PId == f.Id).ToList();
                    //无限循环..
                });
            });
        }


        public List<dynamic> GetRecursionCategory()
        {
           var result = this.RecursionCategory(_respository.Query().ToList(), Guid.Empty);
            return result;
        }

        /// <summary>
        /// 递归分类
        /// </summary>
        public List<dynamic> RecursionCategory(List<CategoryEntity> data, Guid id)
        {
            //先找一级分类
            var list = data.Where(x => x.PId == id).ToList();

            List<dynamic> result = new();

            //然后去一级分类，循环找它对应的二级
            list.ForEach(x =>
            {
                result.Add(new
                {
                    id = x.Id,
                    name = x.Name,
                    icon = x.Icon,
                    items = RecursionCategory(data, x.Id)
                });
            });
            return result;
        }
    }
}
